#!/usr/bin/env ruby
#
# This file is gererated by ruby-glade-create-template 1.1.4.
#
require 'libglade2'
require 'grouhbot.rb'
require 'gnome2'
require 'thread'
require 'gtk_threads.rb'

class RobobuilderGuiGlade
	include GetText

	attr :glade
	attr :connected
	attr :r
	attr :timer
	attr :servo_spin_ids
  attr :pos
  attr :majServos

	def initialize(path_or_data, root = nil, domain = nil, localedir = nil, flag = GladeXML::FILE)
		bindtextdomain(domain, localedir, nil, "UTF-8")
		@glade = GladeXML.new(path_or_data, root, domain, localedir, flag) {|handler| method(handler)}
    @pos = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
		@connected = false
		@psd_enabled = false
		@snd_sampling = false
		@handlers = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
		@servo_spin_ids = [
			"s00_spin", "s01_spin", "s02_spin", "s03_spin", "s04_spin",
			"s05_spin", "s06_spin", "s07_spin", "s08_spin", "s09_spin",
			"s10_spin", "s11_spin", "s12_spin", "s13_spin", "s14_spin",
			"s15_spin"  
		]
	end
	
	def logg(txt)
    puts txt 
		@glade["serialport_log"].buffer.text += txt + "\n"
	end

	def updatePositions
      index = 0 
  		begin  
  			@glade[@servo_spin_ids[index]].signal_handler_block(@handlers[index])
  			@glade[@servo_spin_ids[index]].set_value( @r.wckReadPos(index)[1] )
  			@glade[@servo_spin_ids[index]].signal_handler_unblock(@handlers[index])
        index += 1;
  	  end while index < 16
	end 
	
	def updateAccelerometer
#		xyz = @r.dcmpAccelerometer
#    Gtk.queue do
#  		@glade["accel_x_valueLabel"].text = xyz[0].to_s
#  		@glade["accel_y_valueLabel"].text = xyz[1].to_s
#  		@glade["accel_z_valueLabel"].text = xyz[2].to_s
#  		@glade["accel_x"].value = xyz[0]
#  		@glade["accel_y"].value = xyz[1]
#  		@glade["accel_z"].value = xyz[2]
#    end
	end
	
	def updateSound
		lvl = @r.dcmpGetMicLevel
		@glade["snd_vumetter"].set_fraction((lvl[0] + lvl[1]).to_f / 10.0 )
	end
	
	def updatePSD
		dst = @r.dcmpPSD
		@glade["psd_distance_pb"].set_fraction( dst.to_f / 50.0 )
	end
	
	def servo_spin_changed(widget, servoID)
		begin
			if widget.value <= 360 and widget.value >= 0 
        Thread.new do    
				  @r.wckMovePos servoID, widget.value, 1
        end
			end
		rescue Exception => e
			logg "ERROR while update servo #{servoID}: #{e.message}"
		end
	end

  def test
    t1 = Time.now
    @r.servoID_readservo
    t2 = Time.now
    x = @r.wckReadPos 10
    t3 = Time.now
    puts "A: #{t2 - t1}s"
    puts "B: #{t3 - t2}s"
  end

  def main_onTimeout
    updatePositions 
    #updatePSD if @psd_enabled
    #updateSound if @snd_sampling
    #updateAccelerometer
  end
	def on_connect_btn_clicked(widget)
		serialPort = @glade["serialport_txtfield"].text
		if not @connected
			logg "Trying to connect to port #{serialPort}.."
			begin
				@r = GrouhBot.new( serialPort, true )
        @r.flush
				logg "GrouhBot Connected !"
				#@glade["connect_btn"].text = "Disconnect"
				@connected = true
				
        # Temps de lecture des servos ----------------------
        #x=10;p "Temps moyen: #{((1..x).collect{test}.inject(:+).to_f/x)*1000}ms"
        
				@servo_spin_ids.each_index do |index|
					@handlers[index] = @glade[@servo_spin_ids[index]].signal_connect("value-changed") do
                  #servo_spin_changed(@glade[@servo_spin_ids[index]], index)
          end
			  end
        sleep 0.3
				@timer = Gtk.timeout_add(350){ main_onTimeout; }
			rescue Exception => e
				logg "ERROR: #{e.message}"
				@connected = false
			end
		else
			logg "Disconnecting robot"
			begin
				Gtk.timeout_remove @timer
        @r.flush
				@r.close
				 #@glade["connect_btn"].text = "Connexion"
				@connected = false
			rescue Exception => e
				logg "ERROR: #{e.message}"
				@connected = true
			end
		end
	end

	def on_psd_enabled_toggled(widget)
		@psd_enabled = !@psd_enabled 	
		@r.dcmpPSD( @psd_enabled )
	end

	def on_snd_sampling_toggled(widget)
		@snd_sampling = !@snd_sampling
		@r.dcmpSetSampling( @snd_sampling )
	end
	def on_ruby_cmdline_key_release_event(widget, arg0)
		logg "on_ruby_cmdline_key_release_event() is not implemented yet."
	end
end

# Main program
if __FILE__ == $0
	# Set values as your own application. 
	PROG_PATH = "branches/grouhnet/RoboBuilder_GUI.glade"
	PROG_NAME = "YOUR_APPLICATION_NAME"
	RobobuilderGuiGlade.new(PROG_PATH, nil, PROG_NAME)  
	Gtk.main

	@glade["window"].signal_connect('destroy') do
		Gtk.main_quit
	end
end
